package store.swing.order;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class OrderPanel extends JPanel {
    private JTextField searchField;
    private OrderTable orderTable;

    public OrderPanel() {
        initComponents();
    }

    private void initComponents() {
        setLayout(new GridBagLayout());
        ((GridBagLayout) getLayout()).columnWidths = new int[]{0, 0, 0};
        ((GridBagLayout) getLayout()).rowHeights = new int[]{35, 0, 0};
        ((GridBagLayout) getLayout()).columnWeights = new double[]{0.0, 1.0, 1.0E-4};
        ((GridBagLayout) getLayout()).rowWeights = new double[]{0.0, 1.0, 1.0E-4};

        GridBagConstraints c = new GridBagConstraints();
        c.insets = new Insets(5, 5, 5, 5);
        c.fill = GridBagConstraints.BOTH;

        JLabel searchLabel = new JLabel("Search:");
        c.gridx = 0;
        c.gridy = 0;
        add(searchLabel, c);

        searchField = new JTextField();
        searchField.addKeyListener(new SearchListener());
        c.gridx = 1;
        c.gridy = 0;
        add(searchField, c);

        orderTable = new OrderTable();
        JScrollPane scrollPane = new JScrollPane(orderTable);
        c.gridx = 0;
        c.gridy = 1;
        c.gridwidth = 2;
        add(scrollPane, c);
    }

    private class SearchListener extends KeyAdapter {
        @Override
        public void keyReleased(KeyEvent e) {
            String text = searchField.getText();
            if (text.length() == 0) {
                orderTable.getSorter().setRowFilter(null);
            } else {
                orderTable.getSorter().setRowFilter(RowFilter.regexFilter(text));
            }
        }
    }
}
